import React from "react";
import {
  render as reactRender,
  unmount as reactUnmount,
} from "rc-util/lib/React/render";
import Modal from "./Modal";
import type { ConfirmModalFuncProps, ConfirmModalProps } from "./type";

export default confirm;

let destroyFns: Array<() => void> = [];

function confirm(config: ConfirmModalFuncProps) {
  const div = document.createElement("div");
  document.body.appendChild(div);

  let currentConfig: ConfirmModalProps = { close, visible: true };

  if (typeof config === "string") {
    currentConfig = {
      ...currentConfig,
      title: config,
    };
  } else {
    currentConfig = {
      ...currentConfig,
      ...config,
    };
  }

  function destroy() {
    reactUnmount(div).then((res) => {
      if (div.parentNode) {
        div.parentNode.removeChild(div);
      }
    });
    for (let i = 0; i < destroyFns.length; i++) {
      const fn = destroyFns[i];
      if (fn === close) {
        destroyFns.splice(i, 1);
        break;
      }
    }
  }

  function close() {
    currentConfig = {
      ...currentConfig,
      visible: false,
      afterClose: () => {
        if (
          typeof config !== "string" &&
          typeof config.afterClose === "function"
        ) {
          config.afterClose();
        }
        destroy();
      },
    };
    render(currentConfig);
  }

  function render(props: ConfirmModalProps) {
    setTimeout(() => {
      reactRender(<Modal {...props} />, div);
    });
  }

  return new Promise<void>((resolve, reject) => {
    render({
      ...currentConfig,
      onOk: () => {
        resolve();
      },
      onCancel: () => {
        reject();
      },
    });
    destroyFns.push(close);
  });
}
